package com.ruoyi.web.controller.common;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.system.service.DingSer;
import com.ruoyi.web.controller.tool.JsInvoke;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping(value = "/myrobot")
public class RobotController {
    @Autowired
    private DingSer dingSer;
    /**
     * 校验消息是否合法
     */
    @RequestMapping(value = "/robots", method = RequestMethod.POST)
    public Object helloRobots(@RequestBody(required = false) JSONObject json, HttpServletRequest request) {
        try {
            System.out.println(json.toJSONString());
            //获取请求头header中钉钉发送的timestamp时间戳
            Long dingTimestamp = Long.parseLong(request.getHeader("timestamp"));
            //获取当前时间的时间戳
            Long currentTimeMillis = System.currentTimeMillis();
            //比较两者差值
            Long time = currentTimeMillis - dingTimestamp;
            //获取请求头header中钉钉发送的sign签名
            String dingSign = request.getHeader("sign");
            //开发者后台应用信息中机器人应用的AppSecret
            String appSecret = "5Ttg8yWHiREdK7spVcAWaKplf4qkn1SXblBkBvWmWYPS7tsnpC0_si2vfJhxtnVV";
            //使用请求头header中钉钉发送的timestamp时间戳和开发者后台机器人应用的AppSecret，进行加密操作
            String stringToSign = dingTimestamp + "\n" + appSecret;
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(appSecret.getBytes("UTF-8"), "HmacSHA256"));
            byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
            //获取加密sign
            String sign = new String(Base64.encodeBase64(signData));
            //相差时间在1小时内且sign同时验证通过，才能认为是来自钉钉的合法请求
            if (time < 3600000 && sign.equals(dingSign)) {
                //允许发送范围
                Object filters = JsInvoke.invokeFun(null, "sendPeople");
                String filtersStr = String.valueOf(filters);
                List<String> filtersList = JSON.parseArray(filtersStr, String.class);
                String uid = json.getString("senderStaffId");
                if(filtersList.size()>0){
                    //判断当前账号是在允许发送范围
                    if(!filtersList.contains(uid)){
                        return textMsg("当前账号没有聊天权限!");
                    }
                }
                String content = json.getJSONObject("text").get("content").toString().replaceAll(" ", "");
                System.out.println(content);
                String sessionWebhook = json.getString("sessionWebhook");
                System.out.println(sessionWebhook);
                JSONObject o = null;
                String cc = dingSer.gptChat(uid,content);
                dingSer.sendoToMessages(uid,"sampleMarkdown",markdown(cc).toJSONString());
                System.out.println(cc);
//                o = markdown("hello");
                /*if("文本".equals(content)){
                    o = textMsg();
                }else if("action".equals(content)){
                    dingSer.sendoToMessages(json.getString("senderStaffId"),"sampleActionCard",simpleCard().toJSONString());
                    return null;
                }else{
                    String ss = dingSer.yidaQueryForm(content);
                    dingSer.sendoToMessages(json.getString("senderStaffId"),"sampleText",ss);
                    return null;
                }*/

                return o;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    private JSONObject textMsg(String msg){
        JSONObject o = new JSONObject();
        JSONObject text = new JSONObject();
        o.put("msgtype","text");
        text.put("content",msg);
        o.put("text",text);
        return o;
    }
    private JSONObject markdown(String msg){
        JSONObject text = new JSONObject();
        text.put("text",msg);
        text.put("title","机器人回复");
        return text;
    }
    private JSONObject simpleCard(String cc){
        JSONObject o = new JSONObject();
        o.put("title","");
        o.put("text",cc);
        o.put("singleTitle","https://www.taobao.com");
        o.put("singleURL","https://www.taobao.com");
        return o;
    }
    private JSONObject actionCard(){
        JSONObject o = new JSONObject();
        o.put("title","消息标题测试");
        o.put("text","消息正文测试\nhttps://open.dingtalk.com/document/");
        o.put("actionTitle1","一个按钮");
        o.put("actionURL1","https://www.taobao.com");
        o.put("actionTitle2","两个按钮");
        o.put("actionURL2","https://www.tmall.com");
        return o;
    }
}
